package com.kaizeli.website.controller;

import com.kaizeli.website.response.Result;
import com.kaizeli.website.service.EmployeeActiveImportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * 在职员工导入控制器
 *
 * @author Kaizeli
 * @date 2024-10-21
 */
@Slf4j
@RestController
@RequestMapping("/api/employee-active")
@SecurityRequirement(name = "Bearer Authentication")
@Tag(name = "在职员工导入接口", description = "在职员工Excel导入相关接口")
public class EmployeeActiveImportController {

    @Autowired
    private EmployeeActiveImportService employeeActiveImportService;

    @PostMapping("/import")
    @Operation(summary = "导入在职员工Excel（新增模式）", description = "上传Excel文件，批量导入在职员工数据。如果身份证号已存在则跳过")
    public Result<Map<String, Object>> importEmployeeActiveExcel(
            @RequestParam("file") MultipartFile file) {

        log.info("接收到在职员工导入请求（新增模式），文件名：{}", file.getOriginalFilename());

        try {
            Map<String, Object> result = employeeActiveImportService.importEmployeeActiveExcel(file, false);

            Boolean success = (Boolean) result.get("success");
            if (Boolean.TRUE.equals(success)) {
                return Result.success(result);
            } else {
                return Result.error(500, result.get("message").toString());
            }

        } catch (Exception e) {
            log.error("导入在职员工Excel失败", e);
            return Result.error(500, "导入失败：" + e.getMessage());
        }
    }

    @PostMapping("/import-update")
    @Operation(summary = "导入在职员工Excel（更新模式）", description = "上传Excel文件，批量导入在职员工数据。如果身份证号已存在则更新，不存在则新增")
    public Result<Map<String, Object>> importEmployeeActiveExcelWithUpdate(
            @RequestParam("file") MultipartFile file) {

        log.info("接收到在职员工导入请求（更新模式），文件名：{}", file.getOriginalFilename());

        try {
            Map<String, Object> result = employeeActiveImportService.importEmployeeActiveExcel(file, true);

            Boolean success = (Boolean) result.get("success");
            if (Boolean.TRUE.equals(success)) {
                return Result.success(result);
            } else {
                return Result.error(500, result.get("message").toString());
            }

        } catch (Exception e) {
            log.error("导入在职员工Excel失败", e);
            return Result.error(500, "导入失败：" + e.getMessage());
        }
    }

    @GetMapping("/template")
    @Operation(summary = "下载在职员工导入模板", description = "下载Excel模板文件，用于批量导入在职员工")
    public ResponseEntity<byte[]> downloadTemplate() {

        log.info("接收到下载在职员工模板请求");

        try {
            byte[] templateBytes = employeeActiveImportService.downloadTemplate();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment",
                    java.net.URLEncoder.encode("在职员工导入模板.xlsx", "UTF-8"));

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(templateBytes);

        } catch (Exception e) {
            log.error("下载模板失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    @GetMapping("/import/help")
    @Operation(summary = "获取导入说明", description = "获取在职员工Excel导入的字段说明和注意事项")
    public Result<Map<String, Object>> getImportHelp() {

        Map<String, Object> help = new java.util.HashMap<>();
        help.put("title", "在职员工Excel导入说明");

        Map<String, String> fields = new java.util.HashMap<>();
        fields.put("姓名", "必填，员工姓名");
        fields.put("身份证号", "必填，唯一标识，18位身份证号");
        fields.put("档案号", "选填，员工档案编号");
        fields.put("项目编号", "选填");
        fields.put("客户单位", "选填");
        fields.put("所在部门", "选填");
        fields.put("所在团队", "选填");
        fields.put("岗位名称", "选填");
        fields.put("员工类型", "选填，如：正式员工、实习生等");
        fields.put("性别", "选填");
        fields.put("电话", "选填");
        fields.put("邮箱", "选填");
        fields.put("入职时间", "选填，日期格式");
        fields.put("基本工资", "选填，数字格式");
        help.put("fields", fields);

        java.util.List<String> notes = java.util.Arrays.asList(
                "1. Excel第一行为字段名称，第二行开始为数据",
                "2. 身份证号必须唯一，不能与数据库中已存在的重复",
                "3. 身份证号必须为18位有效格式",
                "4. 建议先下载模板，参考示例数据填写",
                "5. 支持批量导入，单次最多建议不超过1000条",
                "6. 文件格式支持.xlsx和.xls",
                "7. 文件大小不超过10MB"
        );
        help.put("notes", notes);

        return Result.success(help);
    }
}

